import { ThreeSprite } from "../three/sprite";
import { ThreeTexture } from "../three/texture";

export class TextSprite {
    private threeSprite = new ThreeSprite();
    private threeTexture = new ThreeTexture();

    // 创建文字
    make(message: string, parameters?: { [x: string]: any; hasOwnProperty?: any; } | undefined) {
        if (parameters === undefined) parameters = {};
        const fontface = parameters.hasOwnProperty("fontface") ? parameters["fontface"] : "Arial";
        const fontsize = parameters.hasOwnProperty("fontsize") ? parameters["fontsize"] : 32;
        const borderThickness = parameters.hasOwnProperty("borderThickness") ? parameters["borderThickness"] : 4;
        const borderColor = parameters.hasOwnProperty("borderColor") ? parameters["borderColor"] : { r: 0, g: 0, b: 0, a: 1.0 };
        const canvas = document.createElement('canvas');
        const context = canvas.getContext('2d')!;
        context.font = fontsize + "px " + fontface;
        context.measureText(message);
        context.strokeStyle = "rgba(" + borderColor.r + "," + borderColor.g + "," + borderColor.b + "," + borderColor.a + ")";
        context.lineWidth = borderThickness;
        context.fillStyle = "#fffc00";
        context.fillText(message, borderThickness, fontsize + borderThickness);
        context.font = 48 + "px " + fontface;
        const texture = this.threeTexture.canvas(canvas);
        texture.needsUpdate = true;
        const sprite = this.threeSprite.create(texture);
        return sprite;
    }

    // 创建文字精灵
    canvas(text: string) {
        const option = {
            fontFamily: 'Arial',
            fontSize: 30,
            fontWeight: 'bold',
            color: '#ffffff',
            actualFontSize: 0.08,
        };
        const canvas = document.createElement('canvas');
        const context = canvas.getContext('2d')!;
        // 先设置字体大小后获取文本宽度
        context.font = option.fontWeight + ' ' + option.fontSize + 'px ' + option.fontFamily;
        const textWidth = context.measureText(text).width;

        canvas.width = textWidth;
        canvas.height = option.fontSize;

        context.textAlign = "center";
        context.textBaseline = "middle";
        context.fillStyle = option.color;
        context.font = option.fontWeight + ' ' + option.fontSize + 'px ' + option.fontFamily;
        context.fillText(text, textWidth / 2, option.fontSize / 1.8);

        const texture = this.threeTexture.canvas(canvas);
        const spriteObj = this.threeSprite.create(texture);
        spriteObj.scale.set(textWidth / option.fontSize * option.actualFontSize, option.actualFontSize, option
            .actualFontSize);

        return spriteObj;
    }
}